<template>
  <div class="edit-div needsclick" v-html="innerText" ref="editDiv" :contenteditable="canEdit" @input="changeText">
  </div>
</template>
<script type="text/ecmascript-6">
export default {
  name: 'editDiv',
  props: {
    value: {
      type: String,
      default: ''
    },
    canEdit: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      innerText: this.value,
      isLocked: false
    }
  },
  watch: {
    'value' (newValue, oldValue) {
      this.innerText = newValue
      this.$nextTick(() => {
        this.setCaretPosition()
      })
    }
  },
  methods: {
    changeText () {
      this.$emit('input', this.$el.innerHTML)
    },
    setCaretPosition () {  // 设置光标到末尾
      const obj = this.$refs.editDiv
      let range
      if (window.getSelection) {
        obj.focus()
        range = window.getSelection()
        range.selectAllChildren(obj)
        range.collapseToEnd()
      } else if (document.selection) {
        range = document.selection.createRange()
        range.moveToElementText(obj)
        range.collapse(false)
        range.select()
      }
    },
    getCursortPosition () {
      const element = this.$refs.editDiv
      var caretOffset = 0
      var doc = element.ownerDocument || element.document
      var win = doc.defaultView || doc.parentWindow
      var sel
      if (win.getSelection != null) { // 谷歌、火狐
        sel = win.getSelection()
        if (sel.rangeCount > 0) { // 选中的区域
          var range = win.getSelection().getRangeAt(0)
          var preCaretRange = range.cloneRange() // 克隆一个选中区域
          preCaretRange.selectNodeContents(element) // 设置选中区域的节点内容为当前节点
          preCaretRange.setEnd(range.endContainer, range.endOffset)  // 重置选中区域的结束位置
          caretOffset = preCaretRange.toString().length
        }
      } else if ((sel = doc.selection) && sel.type !== 'Control') { // IE
        var textRange = sel.createRange()
        var preCaretTextRange = doc.body.createTextRange()
        preCaretTextRange.moveToElementText(element)
        preCaretTextRange.setEndPoint('EndToEnd', textRange)
        caretOffset = preCaretTextRange.text.length
      }
      return caretOffset
    }
  }
}
</script>
<style lang="stylus" rel="stylesheet/scss">
.edit-div {
  width: 100%;
  height: 100%;
  overflow: auto;
  word-break: break-all;
  outline: none;
  user-select: text;
  white-space: pre-wrap;
  text-align: left;
  img {
    width: 21px;
    height: 21px;
  }

  &[contenteditable='true'] {
    user-modify: read-write-plaintext-only;

    &:empty:before {
      content: attr(placeholder);
      display: block;
      color: #ccc;
    }
  }
}
</style>
